package com.example.soa2.controller;

import com.example.soa2.common.CommonResponse;
import com.example.soa2.entity.UserDTO;
import com.example.soa2.entity.UserProfile;
import com.example.soa2.service.UserService;
import com.example.soa2.vo.UserVO;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/userinfo/")
public class UserController {

    @Autowired
    private UserService userService;
    //获取所有用户信息
    @GetMapping("users")
    @ResponseBody
    public CommonResponse<List<UserVO>> getAllUsers(){
        return CommonResponse.createForSuccess(userService.getAllUsers());
    }
    //根据用户id获取用户信息
    @GetMapping("users/{id}")
    @ResponseBody
    public CommonResponse<UserVO> getUserById(@PathVariable String id){
        UserVO userVO = userService.getUserById(id);
        if(userVO!=null){
            return CommonResponse.createForSuccess(userVO);
        }
        return CommonResponse.createForError("找不到该id用户");
    }
    //TODO 根据用户名获取用户信息
    @GetMapping("users/{name}/name")
    @ResponseBody
    public CommonResponse<UserVO> getUserByName(@PathVariable String name){
        UserVO userVO = userService.getUserByName(name);
        if(userVO!=null){
            return CommonResponse.createForSuccess(userVO);
        }
        return CommonResponse.createForError("找不到该名称的用户");
    }

    @PostMapping("users")
    @ResponseBody
    public CommonResponse<Integer> addNewUserProfile(@Validated @ModelAttribute UserDTO dto){
        return CommonResponse.createForSuccess(userService.addUser(convertProfile(dto)));
    }

    @DeleteMapping("users/{name}")
    @ResponseBody
    public CommonResponse<Integer> deleteUserByName(@PathVariable String name){
        return CommonResponse.createForSuccess(userService.deleteUserByName(name));
    }
    @DeleteMapping("users")
    @ResponseBody
    public CommonResponse<List<Integer>> deleteUser(@RequestParam(value = "userIds") String[] idList){
        return CommonResponse.createForSuccess(userService.deleteUsersByIdList(idList));
    }

    @PutMapping("users/")
    @ResponseBody
    public CommonResponse<Integer> changeUserByName(@Validated @ModelAttribute UserDTO dto){
        System.out.println(convertProfile(dto).getIdentity());
        return CommonResponse.createForSuccess(userService.updateUser(convertProfile(dto)));
    }

    private UserDTO convertProfile(UserDTO dto){
        switch (dto.getIdentity()) {
            case "student" -> dto.setIdentity("1");
            case "teacher" -> dto.setIdentity("2");
            case "administrator" -> dto.setIdentity("3");
        }
        return dto;
    }

}
